const serviceShare = require('@service.share')
const prompt = require('@system.prompt')
const request = require('@system.request')
const media = require('@system.media')
const hook2global = global.__proto__ || global
/** 
 * 生成hash值
*/
function createHash (hashLength) {
  // 默认长度 24
  return Array.from(Array(Number(hashLength) || 24), () => Math.floor(Math.random() * 36).toString(36)).join('')
}
/** 
 * 保存图片到本地
*/
function saveImage(url){
  let imageTypeList=['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
  if(url.indexOf('?')!=-1){
    url=url.substring(0,url.indexOf('?'))
  }
  //获取最后一个.的位置
  var spotIndex= url.lastIndexOf('.')
  let ext=url.substr(spotIndex+1)
  if(imageTypeList.indexOf(ext.toLowerCase()) == -1){
    prompt.showToast({
      message:'请传入图片格式'
    })
    return 
  }
  let imgFinalTipLastIndex=url.lastIndexOf('/',spotIndex)
  let fileName=url.substring(imgFinalTipLastIndex+1,spotIndex)+'.'+ext
  request.download({
    url: url,
    success: data=> {
      request.onDownloadComplete({
        token: data.token,
        success: function(data) {
          console.log(`下载图片成功:${data.uri}`)
          media.saveToPhotosAlbum({
            uri: data.uri,
            success: function() {
              prompt.showToast({
                message:'保存图片成功'
              })
            },
            fail: function(data, code) {
              console.log(`保存图片失败, 错误码：${code}`)
            }
          })
        },
        fail: function(data, code) {
          console.log(`下载图片失败, code = ${code}`)
        }
      })
      console.log(`handling success${data.token}`)
    },
    fail: function(data, code) {
      console.log(`handling fail, code = ${code}`)
    }
  })
}
/** 
 * 分享微信
 * @param {Object} data 
*/

function share(data){
  serviceShare.share({
    shareType: data.shareType,
    title: data.title,
    imagePath: data.imagePath,
    targetUrl: data.targetUrl,
    summary: data.summary ? data.summary : '中青看点',
    platforms: [data.platforms], 
    success: (data) => {
      
    },
    fail: (data, code) => {
      serviceShare.share({
        shareType: 0,
        title: data.title,
        imagePath: data.imagePath,
        targetUrl: data.targetUrl,
        summary: data.summary ? data.summary : '中青看点',
        success: (data) => {
          
        }
      })
    }
  })
}
function  route2theUrl(url, params, clear = false) {
  router.push({
    uri: url,
    params: params
  })
  if (clear) {
    router.clear()
  }
}
/*
 * 获取url后参数
 * @ url 传入的url 
 * @ strname 指定参数
 * */
function getUrlParams(_url,strname){
  let url = _url
  let theRequest = {}
  let urlIndex=url.indexOf('?')
  let urlParams=''
  if(urlIndex!=-1){
    urlParams=url.substring(urlIndex,url.length)
  }
  if (urlParams.indexOf('?') !== -1) {
    let str = urlParams.substr(1)
    let strs = str.split('&')
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1])
    }
  }
  if (strname) {
    return theRequest[strname]
  } else {
    return theRequest
  }
}
/** 
 * 把对象转化成 url携带参数
*/
function changeQueryString(url, query) {
  let str = []
  let index=url.indexOf('#/')
  let beforeStr=url.substring(0,index)
  let endStr=url.substring(index,url.length)
  if(index!=-1){
    url=beforeStr
  }
  let urlParams=getUrlParams(url)
  for (let key in query) {
    if (typeof query[key] === 'object') {
      query[key] = JSON.stringify(query[key])
    }
    if(!urlParams[key]){
      str.push(key + '=' + query[key])
    }
  }
  let paramStr = str.join('&')
  let apiUrl=''
  if(paramStr){
    let params=`${url.indexOf('?')!=-1?'&':'?'}${paramStr}${'&v='+new Date().getTime()}${index!=-1?endStr:''}`
    apiUrl=`${url}${params}`
  }else{
    apiUrl=url
  }
  return apiUrl
}
/**
 * 生成功能唯一key
 * @param {*} name 
 */
function getCurrentDateKey(name){
  var year=new Date().getFullYear()
  var month=new Date().getMonth()+1
  var date=new Date().getDate()
  var currentDayKey=year+month+date
  if(name){
    return name+'_'+currentDayKey
  }
  return currentDayKey
}
/**
 * 将秒转换为 h:m:s 形式 字符串
 * @param {Number} endTime 需要转换的时间  单位 ：s
 * @param {Boolean} isDay 是否要输出天的形式
 */
function getDateTime(endTime){
  const endDate = endTime * 1000 // 结束时间，需传入时间参数
  const t = endDate // 时间差的毫秒数
  let h = 0
  let m = 0
  let s = 0
  // let day = 0
  if (t >= 0) {
    // day = Math.floor(t / 86400 / 1000)
    h = Math.floor((t / 1000 / 60 / 60) % 24)
    m = Math.floor((t / 1000 / 60) % 60)
    s = Math.floor((t / 1000) % 60)

    if (h < 10) {
      h = '0' + h
    }
    if (m < 10) {
      m = '0' + m
    }
    if (s < 10) {
      s = '0' + s
    }
  }
  return{h,m,s}
}
/**
 * 获取签名
 * @param {Object} values 参数集合 
 */
function getSign(values){
  delete values.sign
  let keysArr = []
  const app_secret='jdvylqcGGHHJZrfw0o2DgAbsmBCCGUapF1YChc'
  for(let key in values){
    keysArr.push(key)
  }
  keysArr.sort()
  let keys = ''
  keysArr.forEach((key)=>{
    if(key!='token'){
      keys += key+'='+values[key]
    }
  })
  return hook2global.md5(keys+app_secret)
}

/** 
 * 将剪贴板用&隔开的字符串转化位对象
*/
function toClipboardObj(str){
  let keyValList=str.split('&')
  let obj={}
  keyValList.forEach(item=>{
    let itemArr= item.split('=')
    obj[itemArr[0]]=itemArr[1]
  })
  return obj
}


export default {
  route2theUrl,
  share,
  getUrlParams,
  changeQueryString,
  saveImage,
  createHash,
  getCurrentDateKey,
  getDateTime,
  getSign,
  toClipboardObj
}
